<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="./assets/news.css" />
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
    <script id="tpl-user" type="text/html">
        {{each data}}
        <div class="news-item">
            <img class="thumb" src="{{'http://www.liulongbin.top:3006' + $value.img}}" alt="" />
            <div class="right-box">
                <h1 class="title">{{$value.title}}</h1>
                <div class="tags">
                    {{each $value.tags}}
                    <span>{{$value}}</span> {{/each}}
                </div>

                <div class="footer">
                    <div>
                        <span>{{$value.source}}</span>&nbsp;&nbsp;
                        <span>{{$value.time | dateFormat}}</span>
                    </div>
                    <span>评论数：{{$value.cmtcount}}</span>
                </div>
            </div>
        </div>
        {{/each}}
    </script>
</head>

<body>
    <div id="news-list"></div>
    <script>
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        //定义时间过滤器，用于格式化事件（过滤器定义需要放到template方法之前）
        template.defaults.imports.dateFormat = function(dt) {
            dt = new Date();
            var y = dt.getFullYear();
            var m = padZero(dt.getMonth() + 1);
            var d = padZero(dt.getDate());
            var hh = padZero(dt.getHours());
            var mm = padZero(dt.getMinutes());
            var ss = padZero(dt.getSeconds());
            return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss;
        };

        function loadNewList() {
            $.get('http://www.liulongbin.top:3006/api/news', function(res) {
                // console.log(res);
                if (res.status === 200) {
                    res.data.forEach(function(item) {
                        //让字符串变成数组
                        item.tags = item.tags.split(',');
                    });
                    // var list = res.data;
                    //template的第二个参数是个对象  可以直接传递给模板进行显示
                    var html = template('tpl-user', res);
                    $('#news-list').html(html);
                    console.log(res);
                }
            });
        }
        loadNewList();
    </script>
</body>

</html>